package org.xenon.vote.controller;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xenon.vote.config.UserConfig;
import org.xenon.vote.model.pojo.po.Choice;
import org.xenon.vote.model.pojo.vo.Board;
import org.xenon.vote.model.pojo.vo.Result;
import org.xenon.vote.service.*;
import org.xenon.vote.util.Converter;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@Validated
@RequestMapping("/ballot")
public class BallotController {
    private final BallotService ballotService;
    private final JudgeService judgeService;
    private final ChoiceService choiceService;
    private final TurnService turnService;
    private final BallotManager manager;
    private final UserConfig userConfig;

    public BallotController(BallotService ballotService, JudgeService judgeService,
                            ChoiceService choiceService, TurnService turnService,
                            BallotManager ballotManager, UserConfig userConfig) {
        this.ballotService = ballotService;
        this.judgeService = judgeService;
        this.choiceService = choiceService;
        this.turnService = turnService;
        this.manager = ballotManager;
        this.userConfig = userConfig;
    }

    /**
     * 检查某账号的投票配额是否已满
     */
    @PostMapping("/check/full")
    public Result checkFull(HttpServletRequest req){
        String mail = (String) req.getSession().getAttribute("user");
        if (mail == null) return new Result(false, "login");
        if (userConfig.getBallotLimit() <= ballotService.getTotalBallot(mail))
            return new Result(false, "full");
        else
            return new Result(true, "ok");
    }

    /**
     * 重置一个投票
     * 需要用next开启投票
     *
     * @param id 投票的ID
     */
    @PostMapping("/reset")
    public Result reset(int id, HttpServletRequest req) {
        String mail = (String) req.getSession().getAttribute("user");
        if (!ballotService.checkByBallot(id, mail)) return new Result(false, "login");
        manager.drop(mail);
        ballotService.restart(id);
        return new Result(true, id);
    }


    /**
     * 投票展示页面的信息
     * @return <选项, 票数>
     */
    @GetMapping("/status")
    public Result status (HttpServletRequest req) {
        class Cho {
            String choice;
            int score;

            public Cho(String choice, int score) {
                this.choice = choice;
                this.score = score;
            }

            public String getChoice() {
                return choice;
            }

            public void setChoice(String choice) {
                this.choice = choice;
            }

            public int getScore() {
                return score;
            }

            public void setScore(int score) {
                this.score = score;
            }
        }
        class Res{
            List<Cho> chos;
            boolean end;

            public Res(List<Cho> chos, boolean end) {
                this.chos = chos;
                this.end = end;
            }

            public List<Cho> getChos() {
                return chos;
            }

            public void setChos(List<Cho> chos) {
                this.chos = chos;
            }

            public boolean isEnd() {
                return end;
            }

            public void setEnd(boolean end) {
                this.end = end;
            }
        }
        String mail = (String) req.getSession().getAttribute("user");
        Board board = manager.getBoard(mail);
        if (board == null) return new Result(false, "login");
        HashMap<Choice, Integer> choices = board.getChoices();
        List<Cho> chos = new ArrayList<>();
        for (Choice c : choices.keySet())
            chos.add(new Cho(c.getDetail(), choices.get(c)));
        return new Result(true, new Res(chos, board.check()));
    }

    /**
     * 添加一个投票, 不生成第一轮投票
     *
     * @param name        投票名字
     * @param description 投票描述
     * @param options     选项数据
     * @param judge       裁判数据
     * @return "true" 如果失败.  返回true, 失败名单
     */
    @PostMapping("/add")
    public Result add(String name, String description, String options, String judge, int limit, int option, HttpServletRequest req) {
        String mail = (String) req.getSession().getAttribute("user");
        if (mail == null) return new Result(false, "login");
        if (userConfig.getBallotLimit() <= ballotService.getTotalBallot(mail))
            return new Result(false, "full");
        else {
            System.out.println(userConfig.getBallotLimit());
        }
        //注册投票
        int ballotId = ballotService.add(name, mail, description);
        //注册轮次
        turnService.add(ballotId, limit, option);
        int turnID = turnService.getAll(ballotId).get(0).getId();
        //注册裁判
        List<String> field = judgeService.add(Converter.toJudgeMap(judge), turnID, mail);
        field.add(String.valueOf(turnID));
        //注册选项
        choiceService.addAll(turnID, options.split("\\*"), mail);
        //加入工作序列
        //manager.add(turnID, mail);

        //返回结果
        //有裁判注册失败
        if (field.isEmpty()) return new Result(false, field.toArray(new String[]{}));
        //完全成功
        return new Result(true, ballotId);
    }

    /**
     * 删除投票
     */
    @PostMapping("del")
    public Result del(int id, HttpServletRequest req) {
        String mail = (String) req.getSession().getAttribute("user");
        ballotService.del(id, mail);
        return new Result(true, id);
    }
}











